/**
 * Created by ChenYong on 2017-04-12.
 *
 * 题目列表。
 */

$(function () {
    /** 题目表单 */
    var $questionForm = $("#question_form");
    /** 题目的 jQuery 对象 */
    var $questionTitle = $("#question_title");
    /** 所属行业的 jQuery 对象 */
    var $industryCode = $("#industry_code");
    /** 类型的 jQuery 对象 */
    var $questionType = $("#question_type");
    /** 答案的 jQuery 对象 */
    var $questionAnswer = $("#question_answer");
    /** 开始日期的 jQuery 对象 */
    var $startDate = $("#start_date");
    /** 结束日期的 jQuery 对象 */
    var $endDate = $("#end_date");
    /** 搜索按钮的 jQuery 对象 */
    var $searchQuestionBtn = $("#search_question_btn");
    /** 上传题库按钮的 jQuery 对象 */
    var $uploadQuestionBtn = $("#upload_question_btn");
    /** 题目模态框的 jQuery 对象 */
    var $questionModal = $("#question_modal");
    /** 上传组件的对象 */
    var $questionUploadifive = null;
    /** 题目列表的表格，DataTables 的 API 对象 */
    var questionTable = null;

    // 选择开始日期
    $startDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var startDate = ($.isNull(e.date) ? null : e.date);

        $endDate.datepicker("setStartDate", startDate);
    });

    // 选择结束日期
    $endDate.datepicker({
        format: "yyyy-mm-dd",
        language: "zh-CN",
        clearBtn: true,
        autoclose: true,
        todayHighlight: true
    }).on("changeDate", function (e) {
        var endDate = ($.isNull(e.date) ? null : e.date);

        $startDate.datepicker("setEndDate", endDate);
    });

    // 监听所属行业下拉列表搜索
    $industryCode.change(function () {
        searchData();
    });

    // 监听类型下拉列表搜索
    $questionType.change(function () {
        searchData();
    });

    // 监听答案下拉列表搜索
    $questionAnswer.change(function () {
        searchData();
    });

    // 点击搜索按钮
    $searchQuestionBtn.click(function (e) {
        searchData();
    });

    // 监听题目模态框打开
    $questionModal.on("shown.bs.modal", function () {
        // 将滚动条滚动到顶部
        $questionModal.find(".modal-body").scrollTop("0px");
    });

    // 监听题目模态框关闭
    $questionModal.on("hidden.bs.modal", function () {
        $questionModal.find(".modal-header").find(".modal-title").html("");
        $questionModal.find(".modal-body").html("");
    });

    // 点击查看题目
    $(document).on("click", ".view_question", function () {
        var $this = $(this);
        var id = $this.data("id");

        $.myAjax({
            url: "web/question/detail.html",
            modal: true,
            dataType: "html",
            showHtml: false,
            data: {
                id: $this.data("id")
            },
            successFn: function (data) {
                $questionModal.find(".modal-body").html(data);
                $questionModal.find(".modal-header").find(".modal-title").html($("#question_modal_title").val());

                $questionModal.modal("show");
            }
        });
    });

    // 上传题库
    $questionUploadifive = $uploadQuestionBtn.myUploadifive({
        multi: true,
        width: 80,
        height: 30,
        queueID: "question_queue",
        fileType: ".xls,.xlsx",
        buttonText: "<i class='ace-icon iconfont icon-upload font-size-12'></i>上传题库",
        buttonClass: "btn btn-success btn-xs",
        fileObjName: "uploadExcel",
        uploadScript: "{0}web/question/upload.json".format(globalBasePath),
        fileSizeLimit: String(50 * 1024),
        onQueueCompleteFn: function () {
            // 所有题库上传完毕，刷新题目列表
            if ($.isNotNull(questionTable)) {
                // 重置表单
                $questionForm.get(0).reset();

                searchData();
            }
        }
    });

    // 展示题目表格
    questionTable = $("#question_table").myDataTable({
        url: "web/question/list.json",
        searchBtn: $searchQuestionBtn,
        sScrollY: "450px",
        sScrollX: true,
        sScrollXInner: "100%",
        aaSorting: [[9, "desc"]],
        aLengthMenu: [10, 30, 50, 100],
        aoColumns: [{
            mData: "checkbox",
            sTitle: "<label class='pos-rel' title='全选'><input type='checkbox' class='ace'><span class='lbl'></span></label>",
            sWidth: "50px",
            sClass: "center",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html("<label class='pos-rel'><input type='checkbox' class='ace' data-id='{0}'><span class='lbl'></span></label>".format(rowData.id));
            }
        }, {
            mData: "industryCode",
            sName: "industryCode",
            sTitle: "所属行业",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                if (rowData.industryCode == "A") {
                    $cell.html("煤矿");
                } else if (rowData.industryCode == "B") {
                    $cell.html("非煤矿山");
                } else if (rowData.industryCode == "C") {
                    $cell.html("危化烟花爆竹");
                } else if (rowData.industryCode == "D") {
                    $cell.html("职业健康和工贸");
                } else if (rowData.industryCode == "E") {
                    $cell.html("公共");
                } else if (rowData.industryCode == "F") {
                    $cell.html("八大行业");
                } else if (rowData.industryCode == "X") {
                    $cell.html("其他");
                } else {
                    $cell.html(rowData.industryCode);
                }
            }
        }, {
            mData: "subjectTitle",
            sName: "subjectTitle",
            sTitle: "题目"
        }, {
            mData: "isDouble",
            sName: "isDouble",
            sTitle: "类型",
            sWidth: "60px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                // 单选
                if (rowData.isDouble == "0") {
                    $cell.html("<span class='label label-lg label-success'>单选</span>");

                    // 多选
                } else if (rowData.isDouble == "1") {
                    $cell.html("<span class='label label-lg label-danger'>多选</span>");
                }
            }
        }, {
            mData: "answerA",
            sName: "answerA",
            sTitle: "A选项",
            sWidth: "150px"
        }, {
            mData: "answerB",
            sName: "answerB",
            sTitle: "B选项",
            sWidth: "150px"
        }, {
            mData: "answerC",
            sName: "answerC",
            sTitle: "C选项",
            sWidth: "150px"
        }, {
            mData: "answerD",
            sName: "answerD",
            sTitle: "D选项",
            sWidth: "150px"
        }, {
            mData: "rightAns",
            sName: "rightAns",
            sTitle: "正确答案",
            sWidth: "80px"
        }, {
            mData: "createTime",
            sName: "createTime",
            sTitle: "<i class='ace-icon iconfont icon-time bigger-110'></i>时间",
            sWidth: "100px",
            sDefaultContent: "",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                var $cell = $(cell);

                $cell.html(rowData.createTime.substring(0, 10));
            }
        }, {
            mData: "operator",
            sTitle: "操作",
            sWidth: "100px",
            bSortable: false,
            bSearchable: false,
            sDefaultContent: "<div class='hidden-sm hidden-xs action-buttons'></div>",
            fnCreatedCell: function (cell, cellData, rowData, row, col) {
                // 单元格的 jQuery 对象
                var $cell = $(cell);

                if ($.hasPermission("question:view")) {
                    $cell.find("div.action-buttons").append("<a class='blue view_question' title='查看【{0}】' data-id='{1}' data-toggle='tooltip' data-placement='left' href='javascript:void(0);'><i class='ace-icon iconfont icon-eye bigger-200'></i></a>".format(rowData.subjectTitle, rowData.id));
                }
            }
        }],
        successFn: function () {
            $("[data-toggle='tooltip']").tooltip();
        }
    });

    /**
     *
     * 搜索数据。
     *
     */
    function searchData() {
        // 题目
        if ($.isNotBlank($questionTitle.val()) && ($questionTitle.val().length > 500)) {
            $.toast({
                top: 5,
                msg: "题目的长度不能大于500个字",
                type: "error",
                close: 3000
            });

            return;
        }

        $questionTitle.val($.trim($questionTitle.val()));

        // 搜索开始…
        if ($.isNotNull(questionTable)) {
            questionTable.myAjaxData = {
                endDate: $endDate.val(),
                startDate: $startDate.val(),
                industryCode: $industryCode.val(),
                questionType: $questionType.val(),
                questionTitle: $questionTitle.val(),
                questionAnswer: $questionAnswer.val()
            };

            // 刷新题目表格（分页重置）
            questionTable.ajax.reload();
        }
    }
});